package main

import (
	"html/template"
	"io"
	"net/http"
	"os"

	"github.com/labstack/echo"
)

type User struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
}

type Template struct {
	templates *template.Template
}

func (t *Template) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
	return t.templates.ExecuteTemplate(w, name, data)
}

func main() {
	e := echo.New()
	//模板相关操作，需要的话，增加如下部分
	tpl := &Template{
		templates: template.Must(template.ParseGlob("views/*.html")),
	}
	e.Renderer = tpl

	//普通的请求响应
	e.GET("/", func(c echo.Context) error {
		return c.String(http.StatusOK, "Hello, World!111")
	})
	//url中参数
	e.GET("/hello/:name", func(c echo.Context) error {
		name := c.Param("name")
		return c.String(http.StatusOK, "hello "+name)
	})
	//get参数
	e.GET("/get", func(c echo.Context) error {
		name := c.QueryParam("name")
		age := c.QueryParam("age")
		return c.String(http.StatusOK, "name:"+name+";age:"+age)
	})
	//post表单，及文件
	//curl -v  -X POST -F "name=sucheng" -F "age=0.2" -F "file=@php-7.3.17.tar.gz" http://localhost:8008/form
	e.POST("/form", func(c echo.Context) error {
		name := c.FormValue("name")
		age := c.FormValue("age")
		file, _ := c.FormFile("file")
		moveUploadFile(c, "file")
		return c.String(http.StatusOK, "name:"+name+";age:"+age+";filename:"+file.Filename)
	})

	//下载文件
	e.GET("/file", func(c echo.Context) error {
		return c.File("main.go")
	})

	e.GET("/inline", func(c echo.Context) error {
		// return c.Attachment("attachment.txt", "attachment.txt")
		return c.Inline("main.go", "main.go")
	})

	//静态文件
	e.File("/main.go", "main.go")
	e.Static("static", "static")

	// 模板渲染
	e.GET("/temp", func(c echo.Context) error {
		return c.Render(http.StatusOK, "temp", "temp")
	})

	//响应json
	// curl -v  -X POST -F "name=sucheng" -F "age=12"  http://localhost:8008/json
		user := new(User) if err := c.Bind(user); err != nil {
			return err
		}
		// user := &User{"zhangsan", 10}
		return c.JSON(http.StatusOK, user)
	})

	e.Logger.Fatal(e.Start(":8008"))
}

func moveUploadFile(c echo.Context, name string) bool {
	//获取avatar对象
	upload, err := c.FormFile(name)

	//打开资源文件
	src, err := upload.Open()
	defer src.Close()

	//在服务器端新建一个同名文件 os.Create(“文件名”)
	dst, err := os.Create(upload.Filename)
	defer dst.Close()

	//将传入的文件复制到新建的文件内 io.Copy()
	_, err = io.Copy(dst, src)
	//将第二个参数的内容复制到第一个文件里面去。
	if err != nil {
		return false
	}
	return true
}
